##############################################################################
##
##     Copyright University of Winnipeg, 2008
##     Author: Sydney Weidman s.weidman@uwinnipeg.ca
##
##     This program is free software: you can redistribute it and/or modify
##     it under the terms of the GNU General Public License as published by
##     the Free Software Foundation, either version 3 of the License, or
##     (at your option) any later version.
##
##     This program is distributed in the hope that it will be useful,
##     but WITHOUT ANY WARRANTY; without even the implied warranty of
##     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##     GNU General Public License for more details.
##
##     You should have received a copy of the GNU General Public License
##     along with this program.  If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################

# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from cStringIO import StringIO

from ojsimport.models import Issue

def index(request):
    # List issues
    issues_list = Issue.objects.all()
    return render_to_response('ojsimport/index.html',
                              {'issues_list':issues_list,
                               'user':request.user })

def detail(request, issue_id):
    try:
        issue = Issue.objects.get(pk=issue_id)
    except ObjectDoesNotExist:
        err_msg = 'No issue with id %s' % (issue_id,)
        return render_to_response('ojsimport/index.html',
                                  {'message':err_msg,
                                   'user':request.user })
    return render_to_response('ojsimport/detail.html',
                              {'issue_id':issue_id,
                               'issue_title':issue.title,
                               'user':request.user })
detail = login_required(detail)

def download(request, issue_id):
    try:
        issue = Issue.objects.get(pk=issue_id)
    except ObjectDoesNotExist:
        err_msg = 'No issue with id %s' % (issue_id,)
        return render_to_response('ojsimport/index.html',
                                  {'message':err_msg,
                                   'user':request.user })
    slug = issue.title.replace(' ','_').lower()
    xmlfile = StringIO(issue.asXML())
    response = HttpResponse(xmlfile,mimetype='text/xml')
    response['Content-Disposition'] = 'attachment; filename="%s.xml"' % (slug,)
    return response
download = login_required(download)
